package org.setamv.springcloud.controller;

import org.setamv.springcloud.resttemplate.MyLoadBalanced;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;

@Configuration
@RestController
@RequestMapping("/greetings")
public class GreetingsController {

    /**
     * 该bean在 {@linkplain GreetingsController}中定义，增加了负载均衡注解
     */
    @Autowired
    @Qualifier(value = "loadBalancedRestTemplate")
    private RestTemplate loadBalancedRestTemplate;

    /**
     * 设置了自定义负载均衡的RestTemplate
     * 自定义负载均衡的设置方法参见：{@linkplain org.setamv.springcloud.resttemplate.MyRestTemplateConfiguration}
     */
    @Bean("myLoadBalancedRestTemplate")
    @MyLoadBalanced()
    public RestTemplate getMyLoadBalancedRestTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate;
    }

    @Autowired
    @Qualifier("myLoadBalancedRestTemplate")
    private RestTemplate myLoadBalancedRestTemplate;

    @RequestMapping(value = "/from/{yourName}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object sayHello(@PathVariable String yourName) {
        // 使用spring提供的负载均衡RestTemplate
        String greetings = loadBalancedRestTemplate.getForObject("http://service/service/greetings/from/" + yourName, String.class);

        // 使用自定义的负载均衡RestTemplate。该方法将会调用 MyLoadBalancedInterceptor#intercept方法
        String greetings1 = myLoadBalancedRestTemplate.getForObject("http://service/service/greetings/from/" + yourName, String.class);
        return greetings + "\n" + greetings1;
    }
}
